<template>
  <div class="relative animate-from-right">              
    <div>
      <h2 class="text-[30px] font-bold">欢迎回来 📲 </h2>
      <p class="text-[14px]  --el-text-color-primary mt-[10px] mb-[30px]">请输入您的手机号码以开始管理您的项目</p>
    </div>
      
  
    <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        size="large">
      <el-form-item label="" prop="phone">
        <el-input v-model="ruleForm.phone"  maxlength="11"  placeholder="手机号码"/>

        </el-form-item>
        
        <div class="flex items-center justify-between w-full">
            <div class="flex !w-[63%] code" @paste="handlePaste">
                <el-input v-model="code[i-1]" placeholder="○"  v-for="i in 6" 
              class="!w-[16%] !h-[40px]"
                maxlength="1"
                @focus="activeIndex = i-1"
                @keydown="handleKeyDown($event, i-1)"
                @input="handleInput($event, i-1)"
                ref="inputRefs" />
                
              
            </div>
          
            <el-button size="large" class="bg-color !w-[35%]" @click="sendCode">获取验证码</el-button>
            
        </div>
          <el-form-item label="" prop="code" class="!block">
              <el-input v-model="ruleForm.code"   placeholder="手机号码" v-show="false"/>
            </el-form-item>
      </el-form>
            <el-button type="primary" class="w-full mt-[15px]" @click="submit">登录</el-button>
            <el-button type="default" class="w-full mt-[15px] !ml-[0]" @click="router.go(-1)">返回</el-button>
     
  </div>
</template>

<script setup lang='ts'>





/**路由跳转**/
const router =useRouter()
const goPage=(path:any)=>{
  router.push(path)
}


import type {FormRules} from 'element-plus'
/**获取form**/
const ruleFormRef = ref()


/**提交数据**/
const ruleForm = reactive({
 phone: '',
 code:''
})


 const code = ref(Array(6).fill(''))//验证码数组["","","","","",""]
const activeIndex = ref(0)//当前验证码输入框的索引
const inputRefs = ref<any>([])//输入框的ref值【获取到输入框的原生】


// 处理键盘事件
const handleKeyDown = (e:any, index:any) => {
  console.log(index)

  //console.log(e.key)//键盘按下时出来的键盘值，如按1则返回1
   //code.value[index]//当前输入框的值
   //index循环表单后的(_,index) for 6 也就是表单的序号
   /**
    * 按下的是删除【回退】键
    * 当前输入框的值是空
    * 且当前索引大于0
    * **/
   if(e.key === 'Backspace'&&!code.value[index]&& index > 0){
    //按删除键，当前的索引-1
    activeIndex.value=index-1
    //当前的光标到上一个输入框
    inputRefs.value[activeIndex.value].focus()
   }


}

// 处理输入
const handleInput = (e:any, index:any) => {
  //console.log(e,inputRefs,index)
  //e表示输入了什么值 index当前input的索引
  code.value[index]=e
  if (e && index < 5) {
    activeIndex.value = index + 1
    inputRefs.value[activeIndex.value].focus()
  }
 ruleForm.code=code.value.join('')
}


//粘贴验证码
const handlePaste = (e:any) => {
  console.log(e)
  e.preventDefault()
  const pasteData = e.clipboardData.getData('text/plain').trim()
  if (pasteData.length === 6 && /^\d+$/.test(pasteData)) {
    code.value = pasteData.split('')
     ruleForm.code=pasteData
    // 自动聚焦到最后一个输入框
    activeIndex.value = 5
    inputRefs.value[5].focus()
  }
}


 
 
 
 
//电话号码验证函数
const PhoneValidator= (rule: any, value: any, callback: any)=>{    
  const re = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
  if (!re.test(value)) {
    //表单底部显示的错误信息
    callback(new Error('请输入正确的手机号'));
  }else{
    callback()
  }
}


/**电话号码验证**/
const rules = reactive<FormRules<typeof ruleForm>>({
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    //{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
    { validator:PhoneValidator, trigger: ['blur','change'] }
  ],
  code:[
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { validator:(rule: any, value: any, callback: any)=>{    

  if (value.length!=6) {
    callback(new Error('验证码必须是6位'));
  }else{
    callback()
  }
}, trigger: ['blur','change'] }
  ]
})

const fetchData=(phone:any)=> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const code = '123456'
     
        resolve({ data: code })
      
     
      
    }, 1000)
  })
}

const sendCode=()=>{
ruleFormRef.value.validateField('phone',(valid:any)=>{
  if(valid){
    ElMessage.success('手机号码验证成功');
   
  }else{
    ElMessage.error('表单验证失败');
  }
})
}

const submit = () => {
   console.log(ruleForm.code)
  ruleFormRef.value.validate((valid:any) => {
    //手机验证成功
    if (valid) {
      
      ElMessage.success('验证成功');
      console.log(ruleForm)
      // 这里可以调用API发送验证邮件
    } else {
      ElMessage.error('表单验证失败');
      return false;
    }
  });
};


</script>

<style scoped lang="scss">
 
  
//鼠标悬浮的样式
  .el-input__wrapper:hover {
    border: 1px solid var( --focus-border-color)!important;
    box-shadow: none !important;
  }
//鼠标点击的样式
  .el-input__wrapper.is-focus{
    border: 1px solid var( --focus-border-color)!important;
    box-shadow: none !important;
  }
//原封不动想要修改的样式
  :deep(.code .el-input__wrapper) {
  @apply 
   border-slate-200
  border-[var(--el-border-color)] 
  border-solid 
  rounded-none 
  shadow-none 
  border 

  border-l-0
  overflow-hidden
  p-0
  block;
  
    
  }


  :deep(.code  .el-input:nth-of-type(1) .el-input__wrapper) {
    @apply border-l rounded-l-[5px];
     
  }
   :deep(.code .el-input:nth-last-of-type(1) .el-input__wrapper) {
    @apply rounded-r-[5px]
  }

  :deep(.code .el-input__inner){
    @apply w-[100%] block text-center text-[14px];

  }
  


//   /**去掉数字表单的右侧上下箭头**/
//   :deep(.no_number input::-webkit-inner-spin-button),
// :deep(.no_number input::-webkit-outer-spin-button){
//     -webkit-appearance: none !important;
// }
// :deep(.no_number input[type="number"]) {
//     -moz-appearance: textfield;
// }
 

</style>